<template>
  <div class="app-container">
    <div style="width: 20%">
      <categoryTree @tree-node-click="treeNodeClick"/>
    </div>
    <div style="width: 80%">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="组名" prop="attrGroupName">
          <el-input
            v-model="queryParams.attrGroupName"
            placeholder="请输入组名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="success" icon="el-icon-search" size="mini" @click="handleQueryAll">查询全部</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['group:group:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['group:group:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['group:group:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
            v-hasPermi="['group:group:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="分组id" align="center" prop="attrGroupId" v-if="false"/>
        <el-table-column label="组名" align="center" prop="attrGroupName" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="描述" align="center" prop="descript" />
        <el-table-column prop="icon" label="图标">
          <template slot-scope="{row}">
            <el-image
              style="width: 50px; height: 50px"
              :src="row.icon"
              fit="fill"
              :preview-src-list="[row.icon]"
            />
          </template>
        </el-table-column>
        <el-table-column label="所属分类" align="center" prop="catalogName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-postcard"
              @click="handleRelate(scope.row)"
            >关联</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['group:group:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改属性分组对话框 -->
      <el-dialog :title="title" v-if="open" :close-on-click-modal="false" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="组名" prop="attrGroupName">
            <el-input v-model="form.attrGroupName" placeholder="请输入组名" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="描述" prop="descript">
            <el-input v-model="form.descript" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item label="组图标">
            <imageUpload :maxCount="1" v-model="form.icon"/>
          </el-form-item>
          <el-form-item label="所属分类" prop="catalogId">
            <categoryCascader @handleChange="handleChange" :size="cascaderSize" :cascaderWidth="cascaderWidth" :catelogPath="catalogIds"/>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 关联分类弹出层 -->
      <el-dialog class="pub_dialog" title="关联列表" v-if="openRelate" :close-on-click-modal="false" :visible.sync="openRelate" width="800px"
                 append-to-body>
        <el-form :model="relateQueryParams" ref="relateQueryForm" :inline="true" label-width="68px">
          <el-form-item label="属性名称" prop="name">
            <el-input
              v-model="relateQueryParams.attrName"
              placeholder="请输入属性名称"
              clearable
              size="mini"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="listByAttrId">搜索</el-button>
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multipleRelate" @click="handleRelateDelete">删除</el-button>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddRelate">关联分类</el-button>

          </el-form-item>
        </el-form>
        <el-table v-loading="relateLoading" max-height="300px" @selection-change="handleRelateSelectionChange" :data="relateList">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="属性名" align="center" prop="attrName" />
          <el-table-column label="可选值列表" align="center" prop="valueSelect">

            <template slot-scope="scope">
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-if="scope.row.valueSelect.length>0" v-for="(i,index) in scope.row.valueSelect.toString().split(',')" :key="index">{{i}}<br/></span>
                </div>
                <el-tag v-if="scope.row.valueSelect.length>0">{{scope.row.valueSelect.toString().split(",")[0]+" ..."}}</el-tag>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="属性分组" align="center" prop="attrType" >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.attrType==1">规格参数</el-tag>
              <el-tag v-else type="success">销售属性</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleRelateDelete(scope.row)"
              >移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="totalRelate>0"
          :total="totalRelate"
          :page.sync="relateQueryParams.pageNum"
          :limit.sync="relateQueryParams.pageSize"
          @pagination="listByAttrId"
        />
      </el-dialog>

      <!-- 未关联分类弹出层 -->
      <el-dialog class="pub_dialog" title="未关联列表" v-if="openNoRelate" :close-on-click-modal="false" :visible.sync="openNoRelate" width="750px"
                 append-to-body>
        <el-form :model="noRelateQueryParams" ref="noRelateQueryForm" :inline="true" label-width="68px">
          <el-form-item label="属性名称" prop="name">
            <el-input
              v-model="noRelateQueryParams.attrName"
              placeholder="请输入属性名称"
              clearable
              size="mini"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" clearable size="mini" @click="listByNoAttrId">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="relateLoading" max-height="300px" @selection-change="handleNoRelateSelectionChange" :data="noRelateList">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="属性名" align="center" prop="attrName" />
          <el-table-column label="可选值列表" align="center" prop="valueSelect">
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-if="scope.row.valueSelect.length>0" v-for="(i,index) in scope.row.valueSelect.toString().split(',')" :key="index">{{i}}<br/></span>
                </div>
                <el-tag v-if="scope.row.valueSelect.length>0">{{scope.row.valueSelect.toString().split(",")[0]+" ..."}}</el-tag>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="属性分组" align="center" prop="attrType" >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.attrType==1">规格参数</el-tag>
              <el-tag v-else type="success">销售属性</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="totalNoRelate>0"
          :total="totalNoRelate"
          :page.sync="noRelateQueryParams.pageNum"
          :limit.sync="noRelateQueryParams.pageSize"
          @pagination="listByNoAttrId"
        />
        <div slot="footer" class="dialog-footer">
          <el-button :loading="buttonNoRelateLoading" type="primary" @click="submitSaveRelate">确 定</el-button>
          <el-button @click="openNoRelate=false">取 消</el-button>
        </div>

      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listGroup, getGroup, delGroup, addGroup, updateGroup, exportGroup } from "@/api/mall/pms/attrGroup";
import { delAttrAttrGroup,listByAttrId,addAttrAttrGroup } from "@/api/mall/pms/attrAttrGroup";
import { listByNoAttrId } from "@/api/mall/pms/attr";
import ImageUpload from '@/components/ImageUpload';
import categoryTree from '@/views/components/categoryTree';
import categoryCascader from '@/views/components/category-cascader';

export default {
  name: "Group",
  components: {
    ImageUpload,
    categoryTree,
    categoryCascader
  },
  data() {
    return {
      //级联样式
      cascaderSize:"medium",
	    //按钮loading
	    buttonLoading: false,
	    buttonNoRelateLoading: false,
      // 遮罩层
      loading: true,
      //已关联遮罩层
      relateLoading:true,
      //未关联遮罩层
      noRelateLoading:true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      singleRelate: true,
      singleNoRelate: true,
      // 非多个禁用
      multiple: true,
      multipleRelate: true,
      multipleNoRelate: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 关联总条数
      totalRelate: 0,
      //未关联
      totalNoRelate: 0,
      // 属性分组表格数据
      groupList: [],
      //已关联的属性
      relateList: [],
      //未关联的属性
      noRelateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      openRelate: false,
      openNoRelate: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        attrGroupName: undefined,
        catalogId: undefined
      },
      // 查询参数
      relateQueryParams: {
        pageNum: 1,
        pageSize: 10,
        attrGroupId:undefined,
        catalogId: undefined,
        attrName:undefined
      },
      // 查询参数
      noRelateQueryParams: {
        pageNum: 1,
        pageSize: 10,
        attrGroupId:undefined,
        catalogId: undefined,
        attrName:undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        attrGroupName: [
          { required: true, message: "组名不能为空", trigger: "blur" }
        ],
        catalogId: [
          { required: true, message: "所属分类不能为空", trigger: "blur" }
        ]
      },
      //属性分组id
      attrGroupId:undefined,

      //级联选择器宽度
      cascaderWidth:'380px',
      //分类id组
      catalogIds:[]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //打开分类列表
    handleAddRelate(){
      this.openNoRelate=true;
      this.noRelateLoading = true;
      listByNoAttrId(this.noRelateQueryParams).then(response => {
        this.noRelateList = response.rows;
        this.totalNoRelate = response.total;
        this.noRelateLoading = false;
      }).catch(() => {
        this.noRelateLoading = false;
      });
    },
    // 多选框选中数据
    handleRelateSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.singleRelate = selection.length !== 1
      this.multipleRelate = !selection.length
    },
    // 多选框选中数据
    handleNoRelateSelectionChange(selection) {
      this.ids = selection.map(item => item.attrId)
      this.singleNoRelate = selection.length !== 1
      this.multipleNoRelate = !selection.length
    },
    /** 查询已关联的属性 */
    listByAttrId() {
      this.relateLoading = true;
      listByAttrId(this.relateQueryParams).then(response => {
        this.relateList = response.rows;
        this.totalRelate = response.total;
        this.relateLoading = false;
      }).catch(() => {
        this.relateLoading = false;
      });
    },

    /** 查询未关联的属性 */
    listByNoAttrId() {
      this.noRelateLoading = true;
      listByNoAttrId(this.noRelateQueryParams).then(response => {
        this.noRelateList = response.rows;
        this.totalNoRelate = response.total;
        this.noRelateLoading = false;
      }).catch(() => {
        this.noRelateLoading = false;
      });
    },


    //选择关联的分类
    handleChange(data){
      this.catalogIds=data;
    },
    //点击树节点查询
    treeNodeClick(data){
      if(data.level===3){
        this.queryParams.catalogId=data.id
        this.getList();
      }
    },
    /** 查询属性分组列表 */
    getList() {
      this.loading = true;
      listGroup(this.queryParams).then(response => {
        this.groupList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attrGroupId: undefined,
        attrGroupName: undefined,
        sort: undefined,
        descript: undefined,
        icon: undefined,
        catalogId: undefined
      };
      this.catalogIds=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //查询全部
    handleQueryAll(){
      this.queryParams.catalogId = null;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.attrGroupId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleRelate(row){
      this.openRelate=true;
      //属性分组id
      this.attrGroupId=row.attrGroupId;
      //关联属性 列表查询参数
      this.relateQueryParams.attrGroupId=row.attrGroupId;
      this.noRelateQueryParams.attrGroupId=row.attrGroupId;
      this.noRelateQueryParams.catalogId=row.catalogId;
      this.listByAttrId();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加属性分组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const attrGroupId = row.attrGroupId || this.ids
      getGroup(attrGroupId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.catalogIds=response.data.catalogIds;
        this.open = true;
        this.title = "修改属性分组";
      }).catch(() => {
        this.loading = false;
      });
    },
    //保存关联关系
    submitSaveRelate(){
      if(this.ids.length>0){
        const ids = this.ids;
        let param={
          attrId:ids,
          attrGroupId:this.attrGroupId
        }
        addAttrAttrGroup(param).then(response => {
          this.buttonNoRelateLoading = false;
          this.msgSuccess("保存成功");
          this.openNoRelate = false;
          this.listByAttrId();
        }).catch(() => {
          this.buttonNoRelateLoading = false;
        });
      }


    },
    /** 提交按钮 */
    submitForm() {
      if(this.catalogIds.length==3){
        this.form.catalogId=this.catalogIds[this.catalogIds.length-1];
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.attrGroupId != null) {
            updateGroup(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.queryParams.catalogId=this.form.catalogId;
              this.getList();
            }).catch(() => {
               this.buttonLoading = false;
            });
          } else {
            addGroup(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.queryParams.catalogId=this.form.catalogId;
              this.getList();
            }).catch(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attrGroupIds = row.attrGroupId || this.ids;
      this.$confirm('是否确认删除属性分组编号为"' + attrGroupIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delGroup(attrGroupIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
          this.loading = false;
        });
    },
    /**移除关联关系**/
    handleRelateDelete(row){
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除品牌分类关联编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delAttrAttrGroup(ids);
      }).then(() => {
        this.loading = false;
        this.listByAttrId();
        this.msgSuccess("删除成功");
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有属性分组数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportGroup(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
          this.exportLoading = false;
        });
    }
  }
};
</script>
<style scoped>
  .app-container{
    display: flex;
    justify-content: space-between;
  }
  .pub_dialog {
    display: flex;
    justify-content: center;
    align-items: Center;
  }
  .pub_dialog /deep/ .el-dialog {
    margin: 0 auto !important;
    height: 70%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding-left: 15px;
  }
  .pub_dialog /deep/ .el-dialog .el-dialog__body {
    padding-top: 5px !important;
    overflow: hidden;
    margin-bottom: 40px;
  }
  .pub_dialog /deep/ .el-dialog .el-dialog__footer {
    bottom: 0;
    position: absolute;
    right: 0;
  }
</style>
